package com.thingple.usb.session;

import android.annotation.SuppressLint;
import android.util.Log;

/**
 * 重试/次数控制
 */
public abstract class StreamProcessor extends AbstractUsbSession {

    private static final String TAG = StreamProcessor.class.getName();

    private static final int defaultMaxRework = 5;
    /**
     * 最大重试次数
     */
    private int maxRework = defaultMaxRework;
    /**
     * 当前重试次数,不可设置
     */
    private int reworkTimes = 0;
    /**
     * 是否开始重试
     */
    private boolean reworkEnable = true;
    /**
     * 重试前等待
     */
    private long reworkDelay = 300;
    /**
     * 重试时重置重试次数
     */
    private boolean autoResetRework = true;

    /**
     * 工作状态控制, 只能由start -> true, stop -> false
     */
    protected volatile boolean work;

    /**
     * 默认 defaultMaxRework
     * @param max max
     * {@code Processor.defaultMaxRework}
     */
    public void setMaxRework(int max) {
        maxRework = max;
    }

    /**
     * 打开重试功能, 默认true
     * @param enable 打开
     */
    public void setReworkEnable(boolean enable) {
        reworkEnable = enable;
    }

    /**
     * 重试时自动重置重试次数, 默认true
     * @param enable 使能
     */
    public void setAutoResetRework(boolean enable) {
        autoResetRework = enable;
    }

    /**
     * 重试前等待时间ms, 默认300
     * @param delay 等待ms
     */
    public void setReworkDelay(long delay) {
        reworkDelay = delay;
    }

    protected abstract boolean exec();

    public void loop() {

        try {
            Log.d(TAG, "Session线程开始");
            _loop();
        } catch (Exception e) {
            onTrace("" + e.getMessage());
            onErr(e);
        } finally {
            Log.d(TAG, "Session线程结束");
        }
    }

    @SuppressLint("DefaultLocale")
    private void _loop() {
        while (work) {
            if (reworkTimes >= maxRework) {
                onTrace(String.format("超过最大重连次数[%d],结束session", maxRework));
                return;
            }
            reworkTimes++;

            boolean ok = exec();
            if (ok) {
                continue;
            }

            // 下面处理不OK的情况( •̀_•́ )
            if (reworkEnable) { // 准备重试
                handleResetTimes();
                delay(reworkDelay);
            } else { // 不需要重试
                onTrace("无重连,结束session");
                return;
            }
        }
    }
    private void handleResetTimes() {
        if (autoResetRework) { // 重置次数
            reworkTimes = 0;
        }
    }
    private void delay(long d) {
        try {
            Thread.sleep(d);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void init() {}
}
